Generics

With generics, you can declare and use functions or types that are written to work with any of a set of types provided by calling code.

Add non-generic functions

package main

import "fmt"

func main() {
	ints := map[string]int64{
		"first":  34,
		"second": 12,
	}

	// Initialize a map for the float values
	floats := map[string]float64{
		"first":  35.98,
		"second": 26.99,
	}

	fmt.Printf("Non-Generic Sums: %v and %v\n",
		SumInts(ints),
		SumFloats(floats))
}

func SumInts(nums map[string]int64) int64 {
	var s int64
	for _, val := range nums {
		s += val
	}

	return s
}

func SumFloats(nums map[string]float64) float64 {
	var s float64

	for _, val := range nums {
		s += val
	}

	return s
}

Add generic function

func SumIntsOrFloats[K comparable, V int64 | float64](nums map[K]V) V {
	var s V
	for _, v := range nums {
		s += v
	}

	return s
}

Add generic function using interface

type Number interface {
	int64 | float64
}

func SumNumbers[K comparable, V Number](nums map[K]V) V {
	var s V
	for _, v := range nums {
		s += v
	}

	return s
}